package com.manor.main.fragment.square;

import android.os.Bundle;
import android.view.View;

import com.alibaba.android.arouter.utils.TextUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gyf.immersionbar.ImmersionBar;
import com.orhanobut.logger.Logger;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.manor.common.CommonAppConfig;
import com.manor.common.activity.WebViewActivity;
import com.manor.common.bean.UserBean;
import com.manor.common.event.LocationEvent;
import com.manor.common.http.HttpCallback;
import com.manor.common.http.PitUtil;
import com.manor.common.utils.ClickUtil;
import com.manor.common.utils.KLog;
import com.manor.common.utils.StringUtil;
import com.manor.common.utils.ToastUtil;
import com.manor.im.activity.HChatRoomActivity;
import com.manor.main.R;
import com.manor.main.adapter.MainBottomSameCityAdapter;
import com.manor.main.bean.BottomSameCityBean;
import com.manor.main.event.SelectMainBottomView;
import com.manor.main.fragment.community.CommunityBaseFragment;
import com.manor.main.http.MainHttpUtil;
import com.tencent.imsdk.v2.V2TIMConversation;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * created by Qin
 * on 2020/3/29
 * 首页-同城
 */
public class SquareCityFragment extends CommunityBaseFragment {

    private RecyclerView mRecycleView;
    private MainBottomSameCityAdapter mCityAdapter;


    List<BottomSameCityBean> bottomSameCityBeanList = new ArrayList<>();
    private JSONObject mUserObj;
    private UserBean mUserBean;
    private boolean hasMore = true;
    private String sex = "1";
    private String psex = "1";
    private int pageNum = 1;
    private String isVideo = "";
    private String isVoice = "";
    private String auth = "";
    private String lastId = "";
    private SmartRefreshLayout refreshLayout;


    public static SquareCityFragment newInstance() {
        SquareCityFragment fragment = new SquareCityFragment();
        return fragment;
    }


    @Override
    public void onResume() {
        super.onResume();

    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        KLog.e("tag","isVisibleToUser"+isVisibleToUser);
        if(isVisibleToUser){

        }

    }
    @Override
    protected void initData() {
//        setDate(p);
        getUserInfo();
        EventBus.getDefault().register(this);
        loadDate();
    }

    private void getUserInfo() {
        UserBean userBean = CommonAppConfig.getInstance().getUserBean();
        if (userBean!=null){
            sex = userBean.getSex();
            if (sex.equals("1")) {
                psex = "2";
            } else {
                psex = "1";
            }
        }

    }

    private void loadDate() {

        Logger.e("loadDate pageNum= " + pageNum);
        if (StringUtil.isListNotEmpty(bottomSameCityBeanList)){
            lastId = bottomSameCityBeanList.get(bottomSameCityBeanList.size()-1).getId();
        }else {
            lastId = "";
        }
        setDate(pageNum, psex, auth, isVideo, isVoice, lastId);
    }


    @Override
    public int onSetLayoutId() {
        return R.layout.fragment_square_city;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRecycleView = mContentView.findViewById(R.id.recycler_view);
        refreshLayout = mContentView.findViewById(R.id.refreshLayout);

        mRecycleView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));

        mCityAdapter = new MainBottomSameCityAdapter(R.layout.rv_mainsamecity_item, null);
        mRecycleView.setAdapter(mCityAdapter);


        mCityAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position >= bottomSameCityBeanList.size())
                    return;
                if(bottomSameCityBeanList.get(position).getIsgg().equals("CPM")){
                    if(!TextUtils.isEmpty(bottomSameCityBeanList.get(position).getJump_url())){
                        WebViewActivity.forwars(getActivity(), bottomSameCityBeanList.get(position).getJump_url());
                    }

                    return;
                }

                String toId = bottomSameCityBeanList.get(position).getId();
                if (StringUtil.isNotEmpty(toId)) {
                    if (ClickUtil.canClick()) {
                        EventBus.getDefault().post(new MainOnclickEvent(toId));
//                        if (null != mListener) {
//                            mListener.onItemClick(toId);
//                        }
                    }
                }
                return;

            }
        });

        mCityAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                //获取这个用户的信息，然后跳转去聊天
                if (!"".equals(bottomSameCityBeanList.get(position).getId())) {
                    if (ClickUtil.canClick()) {

                        BottomSameCityBean it = bottomSameCityBeanList.get(position);
                        if(it.getIsgg().equals("CPM")){
                            if( !TextUtils.isEmpty(it.getJump_url())){
                                WebViewActivity.forwars(getActivity(), it.getJump_url());
                            }


                        }else {
                            mUserBean = new UserBean();
                            mUserBean.setUserNiceName(it.getUser_nickname());
                            mUserBean.setFollows(1);
                            mUserBean.setId(it.getId());
                            String avatar = "";
                            if (!"".equals(it.getAvatar())) {
                                avatar = it.getAvatar();
                                mUserBean.setAvatar(it.getAvatar());
                            }
//                        if (!"".equals(it.getThumb())) {
//                            avatar = it.getThumb();
//                            mUserBean.setAvatarThumb(it.getThumb());
//                        }
                            //跳转去聊天
                            //ChatRoomActivity.forward(getContext(), mUserBean, mUserBean.isFollowing(),
                            //       mUserBean.isBlacking(), true, false);

                            if (getActivity()!=null)
                            HChatRoomActivity.Companion.forward(getActivity(), it.getId(), it.getUser_nickname(), avatar,
                                    V2TIMConversation.V2TIM_C2C);


                        }

                    }
                }
            }
        });
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNum++;
                loadDate();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout)
            {
                pageNum = 1;
                loadDate();

            }
        });
    }

    @Override
    public void initView() {



/*        mCityAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mRecycleView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadDate();
                    }
                }, 1000);
//                ToastUtil.show("上拉刷新");
            }
        }, mRecycleView);*/
    }

    /**
     * 更新地图位置后，重新加载当前的列表数据
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLocalSuc(LocationEvent event) {
        Logger.e("onLocalSuc event---");
        if (event != null) {
            pageNum = 1;
            loadDate();
        }

    }

    /**
     * 显示页面后 刷新当前的同城数据
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateBottomView(SelectMainBottomView event) {
        if (event != null) {
            if (event.getSelectView() == 0) {
                Logger.i("调用底部刷新数据----updateBottomView" + event.getSelectView());
                pageNum = 1;
                hasMore = true;
                lastId = "";
                //TODO 是否还要根据上次选择的性别来刷新当前的数据
                setDate(pageNum, psex, auth, "", "", lastId);
            }
        }
    }




    /**
     * 获取用户的信息
     *
     * @param mToUid
     */
    private void getUserDate(String mToUid) {
        MainHttpUtil.getUserHome(mToUid, new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String info) {
                if (code == 0 && StringUtil.isNotEmpty(info)) {
                    String result = PitUtil.strGetFirst(info);

                    setUserObj(JSON.parseObject(result));
                } else {
                    ToastUtil.show(msg);
                }
            }
        });
    }

    private void setUserObj(JSONObject obj) {
        if (obj == null) {
            return;
        }
        mUserObj = obj;
        mUserBean = JSON.toJavaObject(obj, UserBean.class);

        if (mUserObj == null || mUserBean == null) {
            return;
        }


    }

    public JSONObject getUserObj() {
        return mUserObj;
    }

    public UserBean getUserBean() {
        return mUserBean;
    }


    @Override
    public void bindEvent() {

    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(this).statusBarDarkFont(true, 0.2f)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.white)
                .init();
    }

    @Override
    public boolean immersionBarEnabled() {
        return false;
    }

    private void setDate(int p, String sex, String auth, String isvideo, String isVoice, String lastId) {
        MainHttpUtil.getNear(p, sex, auth, isvideo, isVoice, lastId, new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String info) {
                if (code == 0) {
                    if (StringUtil.isNotEmpty(info)) {
                        setCityDate(code, msg, info);
                    } else {
                        hasMore = false;
                    }
                } else {

                }

            }

            @Override
            public void onError() {
                super.onError();
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
                if (mCityAdapter != null) {
                    pageNum--;

                }
            }
        });


    }

    private void setCityDate(int code, String msg, String info) {
        if (code == 0 && StringUtil.isNotEmpty(info)) {
            List<BottomSameCityBean> mList = JSON.parseArray(info, BottomSameCityBean.class);
            if (pageNum == 1) {
                bottomSameCityBeanList.clear();
                mCityAdapter.setNewInstance(mList);
                refreshLayout.finishRefresh();
            }else {
                mCityAdapter.addData(mList);
                refreshLayout.finishLoadMore();
            }
            bottomSameCityBeanList.addAll(mList);


//            for (int i = 0; i < bottomSameCityBeanList.size(); i++) {
//                sameCityList.add(bottomSameCityBeanList);
//            }
            Logger.i("接收到的数据是" + bottomSameCityBeanList.toString());

        }
    }




    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 点击筛选后的条件查询
     *
     * @param filterEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFilterEvent(FilterEvent filterEvent) {
        if (filterEvent != null) {
            psex = filterEvent.getSex();
            byte chatType = filterEvent.getChatType();
            int selectView = filterEvent.getSelectView();
            Logger.i("onFilterEvent接收到的数据是：" + sex + "---" + chatType);


            if (chatType == 0) {
                isVideo = 1 + "";
                isVoice = 1 + "";
            } else if (chatType == 1) {
                isVideo = 1 + "";
                isVoice = 0 + "";
            } else if (chatType == 2) {
                isVideo = 0 + "";
                isVoice = 1 + "";
            }

            if (selectView == 0) {
                Logger.i("调用底部刷新数据" + selectView);
                if (bottomSameCityBeanList.size() > 0) {
                    bottomSameCityBeanList.clear();
                }
                pageNum = 1;
                hasMore = true;
                lastId = "";
                setDate(pageNum, psex, auth, isVideo, isVoice, lastId);
            }

        }
    }

}
